<?php
class CommentController extends Zend_Controller_Action{
	public function preDispatch(){
		$this->_helper->layout()->disableLayout();
	}
	public function indexAction(){
		$this->_helper->viewRenderer->setNoRender(true);
		$news = $this->_getParam('news', null);
		$comMap = new Application_Model_CommentMapper();
		$comments = $comMap->fetchAll($news);
		$json = Zend_Json::encode(array('type'=>'comments','content'=>$comments));
		echo $json;
	}
	public function addAction(){
		$request = $this->getRequest();
		$form = new Application_Form_Comment();
		$this->_helper->Security->removeCaptcha($form);
		
		if($this->getRequest()->isPost()){
			$this->_helper->viewRenderer->setNoRender(true);
			if($form->isValid($request->getPost())){
				$values = $form->getValues();
				$comMap = new Application_Model_CommentMapper();
				$com = new Application_Model_Comment();
				$com	-> setDate(date('d-m-Y H:i:s'))
						-> setPost($values['news'])
						-> setText($values['text'])
						-> setAuthor($this->_helper->Security->userID())
						-> setPseudo($this->_helper->Security->userPseudo());
				$comMap->save($com);
				
				$json = Zend_Json::encode(array('type'=>'addSuccess','content'=>$com));
				echo $json;
			}else{
				$errors = $form->getMessages();
				$messages = array();
				foreach ($errors as $err) {
					foreach($err as $mess){
						$messages[]=$mess;
					}
				}
				$json = Zend_Json::encode(array('type'=>'addError','content'=> $messages));
				echo $json;
			}
		}else{
			$this->view->form = $form;
		}
	}
}